#include "DXUT.h"
#include <PrecompiledHeader.h>
#include "VertexDecl.h"

using namespace d3d11;

VertexDecl::VertexDecl()
:m_pElemLayout(NULL)
{
}

VertexDecl::~VertexDecl()
{
	SAFE_DELETE(m_pElemLayout);
}

void VertexDecl::PushVertexData(VertexData::DataType type, DXGI_FORMAT format, uint size)
{
	VertexData dataDecl;
	dataDecl.Type = type;
	dataDecl.Format = format;	
	dataDecl.Size = size;

	m_pVertexData.push_back(dataDecl);
}

void VertexDecl::ConstructElementLayout()
{
	CASSERT(m_pVertexData.size() > 0, "No elements to construct layout.");

	int iIndexPosition = 0;
	int iIndexColour = 0;
	int iIndexNormal = 0;
	int iIndexTexture = 0;

	SAFE_DELETE(m_pElemLayout);

	m_pElemLayout = new D3D11_INPUT_ELEMENT_DESC[m_pVertexData.size()];

	std::list<VertexData>::iterator i = m_pVertexData.begin();
	int j = 0;
	int iSlot = 0;
	for(;i != m_pVertexData.end(); ++i)
	{
		int iElemSize;

		switch(i->Type)
		{
		case VertexData::POSITION:
			m_pElemLayout[j].SemanticName = "POSITION";
			m_pElemLayout[j].SemanticIndex = iIndexPosition++;
//			iElemSize = 12;
			break;
		case VertexData::COLOUR:
			m_pElemLayout[j].SemanticName = "COLOR";
			m_pElemLayout[j].SemanticIndex = iIndexColour++;
//			iElemSize = 16;
			break;
		case VertexData::TEXTURE:
			m_pElemLayout[j].SemanticName = "TEXCOORD";
			m_pElemLayout[j].SemanticIndex = iIndexTexture++;
//			iElemSize = 8;
			break;
		case VertexData::NORMAL:
			m_pElemLayout[j].SemanticName = "NORMAL";
			m_pElemLayout[j].SemanticIndex = iIndexNormal++;
//			iElemSize = 12;
			break;
		};

		iElemSize = i->Size;

		m_pElemLayout[j].Format = (DXGI_FORMAT)i->Format;

		m_pElemLayout[j].AlignedByteOffset = iSlot;
		m_pElemLayout[j].InputSlot = 0;
		m_pElemLayout[j].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
		m_pElemLayout[j].InstanceDataStepRate = 0;

		iSlot += iElemSize;
		j++;
	}
}
